package cn.ligoo.part.web.springmvc;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.WebUtils;

import cn.ligoo.part.domain.SysModAction;
import cn.ligoo.part.domain.SysModule;
import cn.ligoo.part.domain.UserInfo;
import cn.ligoo.part.service.impl.FacadeImpl;
import cn.ligoo.part.web.Constants;
import cn.ligoo.part.web.ControllerUtils;

@Controller
public class DefaultController {

	private final Logger logger = LoggerFactory.getLogger(DefaultController.class);

	@Resource
	private FacadeImpl facade;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index() {
		return "redirect:/login";
	}

	@RequestMapping(value = "/platform/{page}", method = RequestMethod.GET)
	public String gotoView(HttpServletRequest request, @PathVariable String page, @RequestParam Integer mod_code,
			Model model) {
		// 每个叶子节点的模块（有具体操作）都有自己可授权的权限
		// 每个人对应的角色对此栏目都有授权
		// 特殊情况：管理员，公共模块
		// 注意：模块授权的权限可能和角色对应的权限不同步，
		// 例如某模块一开始全部可授权，每用户获得了全部授权，后来管理员收回了部分授权，但角色里的授权还没有变！

		if (null == mod_code) {
			return "/platform/" + page;
		}

		SysModule t = new SysModule();
		t.setMod_code(mod_code);
		SysModule sysModule = facade.getSysModuleService().getSysModule(t);
		if (null != sysModule) {
			String action_codes = sysModule.getAction_codes();
			UserInfo userInfo = (UserInfo) WebUtils.getSessionAttribute(request, Constants.SESSION_USER_INFO);
			List<SysModAction> sysModActionList = ControllerUtils.getSysModActionList(facade, userInfo);
			if (null == sysModActionList) { // 管理员可能没有授权，当然也可以授权
				if (userInfo.getIs_admin() == 1) { // 直接可以操作栏目本身可授权的所有权限
					logger.debug("action_codes:={}", action_codes);
					model.addAttribute("action_codes", action_codes);
				}
			} else {
				List<String> actionList = new ArrayList<String>();
				for (SysModAction sma : sysModActionList) {
					if (sma.getMod_code() == sysModule.getMod_code() && action_codes.contains(sma.getAction_code())) {
						actionList.add(sma.getAction_code());
					}
				}
				action_codes = StringUtils.join(actionList, ",");
				logger.debug("action_codes:={}", action_codes);
				model.addAttribute("action_codes", action_codes);
			}
		}
		return "/platform/" + page;
	}
}
